package com.zs.propertymanage.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtUtil {
    public static String generateToke(Map<String, String> userInfo) {
        return JWT.create()
                .withClaim("loginUser", userInfo)
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60 * 3))    // 3小时过期
                .sign(Algorithm.HMAC256("GXWY_ZhangShun"));
    }

    public static Map<String, Object> parseToken(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256("GXWY_ZhangShun")).build();
        DecodedJWT decodedJWT = verifier.verify(token);
        Map<String, Claim> claims = decodedJWT.getClaims();
        return claims.get("loginUser").asMap();
    }

    // 将对象转换为map，键为属性名，值为属性值
    public static Map<String, Object> obj2Map(Object obj) {
        if (obj == null) {
            return new HashMap<>();
        }

        Class<?> clazz = obj.getClass();
        Map<String, Object> map = new HashMap<>();

        for (Field field : clazz.getDeclaredFields()) {
            // 允许访问私有字段
            field.setAccessible(true);

            if (Modifier.isStatic(field.getModifiers()))
                continue;   // 跳过静态字段

            String fieldName = field.getName();
            Object value = null;
            try {
                value = field.get(obj);
//                value = field.get(obj) == null ? "" : field.get(obj);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

            map.put(fieldName, value);
        }

        return map;
    }
}
